﻿using Newtonsoft.Json;
using PrintPeceipt.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PrintPeceipt
{
    public partial class ImportForm : Form
    {
        public MainForm Owner;

        //public ImportForm()
        //{
        //    InitializeComponent();
        //}

        public ImportForm(MainForm owner)
        {
            Owner = owner;
            InitializeComponent();
            var defaultJsonFile = System.Environment.CurrentDirectory + "\\Data.json";
            this.txtJson.Text = File.ReadAllText(defaultJsonFile, Encoding.GetEncoding("GB2312"));
        }

        private void btnInmport_Click(object sender, EventArgs e)
        {
            var address = this.txtAddress.Text;
            if(string.IsNullOrEmpty(address))
            {
                MessageBox.Show("请输入地址");
                return;
            }
            string getJson = HttpUitls.Get(address);
            if (string.IsNullOrEmpty(address))
            {
                MessageBox.Show("获取内容为空");
                return;
            }

            try
            {
                var peceipts = JsonConvert.DeserializeObject<Peceipts>(getJson);
                var json = JsonConvert.SerializeObject(peceipts, Formatting.Indented);
                this.txtJson.Text = json;
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取内容格式不正确");
                this.txtJson.Text = getJson;
            }            
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            var json = this.txtJson.Text;
            var peceipts = JsonConvert.DeserializeObject<Peceipts>(json);
            Owner.peceipts = peceipts;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
